package cn.huiyunche.base.service.interfaces.impl;

import cn.huiyunche.base.service.interfaces.TmsOrderCallHistoryService;
import cn.huiyunche.base.service.mappers.TmsOrderCallHistoryMapper;
import cn.huiyunche.base.service.model.TmsOrderCallHistory;
import cn.huiyunche.base.service.model.TmsOrderCallHistoryExample;
import cn.huiyunche.base.service.utils.DateUtils;
import cn.huiyunche.base.service.utils.HttpRequestUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @FileName: cn.huiyunche.service.base.interfaces.tms.impl
 * @Description: Description
 * @author: Aaron
 * @date: 2016/11/3 上午10:40
 */
@Service
public class TmsOrderCallHistoryServiceImpl implements TmsOrderCallHistoryService {

    private static final Logger LOGGER = LoggerFactory.getLogger(TmsOrderCallHistoryServiceImpl.class);

    @Autowired
    private TmsOrderCallHistoryMapper tmsOrderCallHistoryMapper;

    @Override
    public void add(TmsOrderCallHistory callHistory) {
        LOGGER.info("add param : {}", callHistory);
        if (null == callHistory) {
            LOGGER.error("add param callHistory must not be null");
            throw new IllegalArgumentException("调用历史记录不能为空");
        }
        tmsOrderCallHistoryMapper.insertSelective(callHistory);
    }

    @Override
    public void update(TmsOrderCallHistory callHistory) {
        LOGGER.info("update param : {}", callHistory);
        if (null == callHistory) {
            LOGGER.error("add param callHistory must not be null");
            throw new IllegalArgumentException("调用历史记录不能为空");
        }
        tmsOrderCallHistoryMapper.updateByPrimaryKeySelective(callHistory);
    }

    @Override
    public Date getLastTimeSuccess(String url, Boolean isSuccessful) {
        LOGGER.info("getLastTimeSuccess params : {}, {}", url, isSuccessful);
        if (StringUtils.isBlank(url)) {
            LOGGER.error("getLastTimeSuccess param url must not be null");
            throw new IllegalArgumentException("url不能为空");
        }
        if (null == isSuccessful) {
            isSuccessful = true;
        }

        TmsOrderCallHistoryExample example = new TmsOrderCallHistoryExample();
        example.setOrderByClause(" create_time DESC limit 1");
        example.createCriteria().andTmsUrlEqualTo(url).andSuccessEqualTo(true);

        List<TmsOrderCallHistory> list = tmsOrderCallHistoryMapper.selectByExample(example);
        if (CollectionUtils.isNotEmpty(list)) {
            return list.get(0).getTmsSystemQueryTime();
        }

        //当天0点
        Date todayStart = DateTime.now()
                .hourOfDay().withMinimumValue()
                .minuteOfHour().withMinimumValue()
                .secondOfMinute().withMinimumValue()
                .millisOfSecond().withMinimumValue()
                .toDate();

        return todayStart;
    }

    @Override
    public Date getLastTimeSuccess(int type, Boolean isSuccessful) {
        LOGGER.info("getLastTimeSuccess params : {}, {}", type, isSuccessful);
        if (type <= 0) {
            LOGGER.error("getLastTimeSuccess param url must not be null");
            throw new IllegalArgumentException("url不能为空");
        }
        if (null == isSuccessful) {
            isSuccessful = true;
        }

        TmsOrderCallHistoryExample example = new TmsOrderCallHistoryExample();
        example.setOrderByClause(" create_time DESC limit 1");
        example.createCriteria().andTmsUrlTypeEqualTo(type).andSuccessEqualTo(true);

        List<TmsOrderCallHistory> list = tmsOrderCallHistoryMapper.selectByExample(example);
        if (CollectionUtils.isNotEmpty(list)) {
            return list.get(0).getTmsSystemQueryTime();
        }

        // 当天0点
        Date todayStart = DateTime.now().hourOfDay().withMinimumValue().minuteOfHour().withMinimumValue()
                .secondOfMinute().withMinimumValue().millisOfSecond().withMinimumValue().toDate();

        return todayStart;
    }

    @Override
    public String urlCall(final String url, int urlType, final Map<String, Object> paramsMap, final int socketTimeout) {
        //接口调用记录
        TmsOrderCallHistory callHistory = new TmsOrderCallHistory();
        callHistory.setSuccess(false);
        callHistory.setTmsUrlType(urlType);
        callHistory.setTmsUrl(url);
        callHistory.setPullOrPush(0);
        callHistory.setParameters(JSONObject.toJSONString(paramsMap));
        callHistory.setCallStartTime(new Date());
        //保存调用记录
        this.add(callHistory);
        try {
            String result = HttpRequestUtil.sendHttpPost(url, paramsMap, socketTimeout);
            callHistory.setResultContent(result);
            callHistory.setCallEndTime(new Date());
            LOGGER.info("urlCall url:{}, result: {}", url, result);
            if (StringUtils.isNotBlank(result)) {
                JSONObject object = JSONObject.parseObject(result);
                boolean success = object.getBoolean("success");
                callHistory.setSuccess(success);
                callHistory.setMessage(object.getString("message"));
                callHistory.setMessageCode(object.getString("messagecode"));
                if (success) {
                    String data = object.getString("data");
                    JSONObject dataObj = JSONObject.parseObject(data);
                    String dataString = dataObj.getString("data");
//                    Object lastTimeStr = paramsMap.get("lastTime");
                    Object lastTimeStr = dataObj.get("timestamp");
                    if (null != lastTimeStr) {
                        callHistory.setTmsSystemQueryTime(DateUtils.StrToDate(lastTimeStr.toString(), DateUtils.YYYY_MM_DD_HH_MM_SS_SSS));
                    }
                    if (StringUtils.isNotBlank(dataString)) {
                        JSONArray list = JSONArray.parseArray(dataString);
                        if (null != list) {
                            callHistory.setResultCount(list.size());
                        }
                    }
                    //更新调用记录
                    this.update(callHistory);
                    return data;
                }
                //更新调用记录
                this.update(callHistory);
                return null;
            }
        } catch (Exception e) {
            LOGGER.error("urlCall getData : {}", e);
            callHistory.setCallEndTime(new Date());
            callHistory.setMessage("调用失败！");
            callHistory.setMessageCode("500");
        }

        return null;
    }

}
